package com.tom.commonframework.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Looper;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;

import com.tom.commonframework.R;

/**
 * @author liguoshuai
 * @category 底部导航栏
 */
public class TabButton extends View {
    private Bitmap mBitmap;
    private Bitmap mClickBitmap;
    private int mColor = 0xFFAAAAAA;
    private int mClickColor = 0xFF3F9FE0; // 0x00D294;
    private int mColor_message = 0xFFFF0000;
    private float mTextSize;
    private String mText = "";
    private float mAlpha = 0f;
    private Rect mBitmapRect;
    private Rect mTextRect;
    private Paint mTextPaint;
    private int mMessageNumber = 0;

    public TabButton(Context context) {
        this(context, null);
    }

    public TabButton(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }


    public TabButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TabButton);

        int n = a.getIndexCount();

        for (int i = 0; i < n; i++) {
            int attr = a.getIndex(i);
            if (attr == R.styleable.TabButton_image) {
                BitmapDrawable drawable = (BitmapDrawable) a.getDrawable(attr);
                mBitmap = drawable.getBitmap();
            } else if (attr == R.styleable.TabButton_clickimage) {
                BitmapDrawable clickdrawable = (BitmapDrawable) a.getDrawable(attr);
                mClickBitmap = clickdrawable.getBitmap();
            } else if (attr == R.styleable.TabButton_clickcolor) {
                mClickColor = a.getColor(attr, 0xFF3F9FE0);
            } else if (attr == R.styleable.TabButton_text) {
                mText = a.getString(attr);
            } else if (attr == R.styleable.TabButton_text_size) {
                mTextSize = a.getDimension(attr, 12);
            }
        }

        a.recycle();

        mTextRect = new Rect();
        mTextPaint = new Paint();
        mTextPaint.setTextSize(mTextSize);
        mTextPaint.getTextBounds(mText, 0, mText.length(), mTextRect);
        mTextPaint.setAntiAlias(true);// 抗锯齿

    }
    public static int dip2px(Context context, float dpValue) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();

        float xdpi = dm.xdpi;
        float ydpi = dm.ydpi;
        int width = dm.widthPixels;
        int height = dm.heightPixels;
        float w = width / xdpi;
        float h = height / ydpi;
        float size = (float) Math.sqrt(w * w + h * h);
        float rate;
        if (size > 6) {
            rate = size / 4;
        } else {
            rate = size / 8;
        }
        final float scale = dm.density;
        return (int) (dpValue * scale * rate + 0.5f);

    }
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int padding = dip2px(getContext(), 4);
        int iconWidth = Math.min(getMeasuredWidth() - padding * 2,
                getMeasuredHeight() - padding * 2 - mTextRect.height());

        int left = getMeasuredWidth() / 2 - iconWidth / 2;
        int top = getMeasuredHeight() / 2 - (mTextRect.height() + iconWidth) / 2;
        mBitmapRect = new Rect(left, top, left + iconWidth, top + iconWidth);

    }

    @Override
    protected void onDraw(Canvas canvas) {
        int alpha = (int) Math.ceil(255 * mAlpha);

        if (alpha < 1) {
            drawText(canvas, 255, mColor);
            drawBitmap(canvas, 255, mColor, mBitmap);
        } else {
            drawText(canvas, alpha, mClickColor);
            drawBitmap(canvas, alpha, mClickColor, mClickBitmap);
        }
        if (mMessageNumber > 0) {
            drawMessages(canvas);
        }

    }

    /**
     * 绘制文本
     *
     * @param canvas
     * @param alpha
     * @param color
     */
    private void drawText(Canvas canvas, int alpha, int color) {
        mTextPaint.setColor(color);
        mTextPaint.setAlpha(alpha);
        int x = getMeasuredWidth() / 2 - mTextRect.width() / 2;
        int y = mBitmapRect.bottom + mTextRect.height();
        canvas.drawText(mText, x, y, mTextPaint);

    }

    /**
     * 画图标
     *
     * @param canvas
     * @param alpha
     * @param color
     * @param bitmap
     */
    private void drawBitmap(Canvas canvas, int alpha, int color, Bitmap bitmap) {
        try {
            Bitmap bitmapTem = Bitmap.createBitmap(getMeasuredWidth(), getMeasuredHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvasTem = new Canvas(bitmapTem);
            Paint paint = new Paint();
            canvasTem.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));
            paint.setColor(color);
            paint.setAlpha(alpha);
            canvasTem.drawRect(mBitmapRect, paint);
            paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
            canvasTem.drawBitmap(bitmap, null, mBitmapRect, paint);
            canvas.drawBitmap(bitmapTem, 0, 0, null);
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }

    /**
     * 画消息数量
     *
     * @param canvas
     */
    private void drawMessages(Canvas canvas) {
        int num = mMessageNumber;
        if (num > 0) {
            int width = mBitmapRect.width();
            float radius1 = width / 5;

            Paint paint = new Paint();
            paint.setXfermode(new PorterDuffXfermode(Mode.SRC_OVER));
            paint.setAntiAlias(true);

            paint.setColor(mColor_message);
            paint.setStyle(Paint.Style.FILL);
            canvas.drawCircle(mBitmapRect.right - radius1, width / 2, radius1, paint);

            String showStr = String.valueOf(num);
            if (num > 99)
                showStr = "99+";
            if (num <= 0)
                showStr = "";
            float textSize = width / 6;
            float x = 0;
            if (num < 10) {
                textSize = radius1 + 5;
                // textSize = ScreenVar.dip2px(getContext(), 6);
                x = mBitmapRect.right - radius1;
            } else if (num < 100) {
                textSize = radius1 + 2;
                // textSize = ScreenVar.dip2px(getContext(), 5);
                x = mBitmapRect.right - radius1 - textSize / 8;
            } else {
                textSize = radius1;
                // textSize = ScreenVar.dip2px(getContext(), 3);
                x = mBitmapRect.right - radius1 - textSize / 8;
            }

            paint.setColor(0xDDFFFFFF);
            // paint.setFakeBoldText(true);
            paint.setTextSize(textSize);
            paint.setTypeface(Typeface.MONOSPACE);
            paint.setTextAlign(Paint.Align.CENTER);
        }
    }

    public void addMessageNumber(int number) {
        mMessageNumber += number;
        invalidateView();
    }

    public void setAlpha(float alpha) {
        this.mAlpha = alpha;
        invalidateView();
    }

    public void setText(String text) {
        mText = text;
        mTextRect = new Rect();
        mTextPaint = new Paint();
        mTextPaint.setTextSize(mTextSize);
        mTextPaint.getTextBounds(mText, 0, mText.length(), mTextRect);
        mTextPaint.setAntiAlias(true);
    }

    private void invalidateView() {
        if (Looper.getMainLooper() == Looper.myLooper()) {
            invalidate();
        } else {
            postInvalidate();
        }
    }

    private static final String INSTANCE_STATUS = "instance_status";
    private static final String STATUS_ALPHA = "status_alpha";

    @Override
    protected Parcelable onSaveInstanceState() {
        Bundle bundle = new Bundle();
        bundle.putParcelable(INSTANCE_STATUS, super.onSaveInstanceState());
        bundle.putFloat(STATUS_ALPHA, mAlpha);
        return bundle;
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        if (state instanceof Bundle) {
            Bundle bundle = (Bundle) state;
            mAlpha = bundle.getFloat(STATUS_ALPHA);
            super.onRestoreInstanceState(bundle.getParcelable(INSTANCE_STATUS));
            return;
        }
        super.onRestoreInstanceState(state);
    }

    public void setNumInImage(Integer consultTotal) {
        if (consultTotal == null)
            mMessageNumber = 0;
        else
            mMessageNumber = consultTotal;

        invalidateView();
    }
}
